package com.lbd.project.service.impl;

/**
 * Created by Yuanbo on 2016/9/29.
 * <p>
 * 标的审核列表
 *
 * @param targetInfo 标的查询条件信息
 * @param parameter  map参数
 * @return 分页列表
 * <p>
 * 借款中的项目列表
 * @param page     页码
 * @param rows     行数
 * @param targetVo 标的类
 * @return 分页后的借款列表
 * <p>
 * 获取某个标的的投资情况
 * @param page     页码
 * @param rows     行数
 * @param targetId 标的id
 * @return 投资列表
 * <p>
 * 投资情况中的-某笔投资的总投资人数,总投资金额
 * @param targetId 标的id
 * @return 投资总人数\总金额
 * <p>
 * 贷前中理-流标中的项目列表
 * @param page     页码
 * @param rows     行数
 * @param targetVo 筛选条件
 * @return 流标中的项目列表
 * <p>
 * 更新审核后的标的信息
 * @param targetId    标的id
 * @param auditStatus 审核状态
 * @param suggestion  审核意见
 * @param mjStart     募集开始时间
 * @param rzqx        融资期限
 * @return 审核后的标的信息
 * <p>
 * 删除风控信息图片
 * @param targetId    标的id
 * @param fileContent 文件保存路径
 * <p>
 * 更新风控信息图片
 * @param oType       文件类型
 * @param fileContent 文件保存路径
 * @param targetId    标的id
 * @return 更新风控信息图片
 * <p>
 * 更新标的信息
 * @param targetVo 要更新的字段
 * <p>
 * 查询已满标项目
 * @param page
 * @param rows
 * @param targetVo
 * @return 满标放款
 * @param targetId 标的
 * <p>
 * 获取募集结束日期
 * @param rzqx       融资期限
 * @param targetInfo 标的信息
 * <p>
 * 标的审核列表
 * @param targetInfo 标的查询条件信息
 * @param parameter  map参数
 * @return 分页列表
 * <p>
 * 借款中的项目列表
 * @param page     页码
 * @param rows     行数
 * @param targetVo 标的类
 * @return 分页后的借款列表
 * <p>
 * 获取某个标的的投资情况
 * @param page     页码
 * @param rows     行数
 * @param targetId 标的id
 * @return 投资列表
 * <p>
 * 投资情况中的-某笔投资的总投资人数,总投资金额
 * @param targetId 标的id
 * @return 投资总人数\总金额
 * <p>
 * 贷前中理-流标中的项目列表
 * @param page     页码
 * @param rows     行数
 * @param targetVo 筛选条件
 * @return 流标中的项目列表
 * <p>
 * 更新审核后的标的信息
 * @param targetId    标的id
 * @param auditStatus 审核状态
 * @param suggestion  审核意见
 * @param mjStart     募集开始时间
 * @param rzqx        融资期限
 * @return 审核后的标的信息
 * <p>
 * 删除风控信息图片
 * @param targetId    标的id
 * @param fileContent 文件保存路径
 * <p>
 * 更新风控信息图片
 * @param oType       文件类型
 * @param fileContent 文件保存路径
 * @param targetId    标的id
 * @return 更新风控信息图片
 * <p>
 * 更新标的信息
 * @param targetVo 要更新的字段
 * <p>
 * 查询已满标项目
 * @param page
 * @param rows
 * @param targetVo
 * @return 满标放款
 * @param targetId 标的
 * <p>
 * 获取募集结束日期
 * @param rzqx       融资期限
 * @param targetInfo 标的信息
 *//*
@Service
@Transactional
public class TargetServiceImpl extends BaseServiceImpl<TargetInfo, TargetRepository> implements TargetService {
    private final Logger log = Logger.getLogger(this.getClass());

    @Autowired
    TargetRepository targetRepository;
    @Autowired
    TargetService targetService;
    @Autowired
    UserService userService;

    @Value("${coreUrl}")
    private String CORE_URL;


    *//**
 * 标的审核列表
 *
 * @param targetInfo 标的查询条件信息
 * @param parameter  map参数
 * @return 分页列表
 *//*
    @Override
    public String buildJpql(TargetInfo targetInfo, Map<String, Object> parameter) {
        TargetVo targetVo = (TargetVo) targetInfo;
        StringBuilder jpqlBuilder = new StringBuilder(" from TargetInfo t");
        if (null != targetVo) {
            getTargetParams(targetVo, jpqlBuilder, parameter);
            //审核状态
            if (StringUtils.isNotBlank(targetVo.getAuditStatus())) {
                jpqlBuilder.append(" and t.auditStatus =:auditStatus");
                parameter.put("auditStatus", targetVo.getAuditStatus());
            }
            //时间区间
            if (null != targetVo.getStartTime()) {
                jpqlBuilder.append(" and DATE_FORMAT(created_date,'%Y-%m-%d %H:%i:%s') >=:startTime");
                parameter.put("startTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(targetVo.getStartTime()));
            }
            if (null != targetVo.getEndTime()) {
                jpqlBuilder.append(" and DATE_FORMAT(created_date,'%Y-%m-%d %H:%i:%s') <=:endTime");
                parameter.put("endTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(targetVo.getEndTime()));
            }

        }
        jpqlBuilder.append(" order by t.createdDate desc");
        return jpqlBuilder.toString();
    }

    *//**
 * 借款中的项目列表
 *
 * @param page     页码
 * @param rows     行数
 * @param targetVo 标的类
 * @return 分页后的借款列表
 *//*
    @Override
    public Page<Map> findLoansList(int page, int rows, TargetVo targetVo) {
        StringBuilder jpqlBuilder = new StringBuilder(
                "select id, loan_number as loanNumber, telephone AS telephone," +
                        "bdrealname AS bdrealname,productid AS productid," +
                        "htje AS htje," + "htqx AS htqx," + "nhsyl AS nhsyl," + "hkfs AS hkfs," +
                        "created_date AS createdDate, rzqx, mj_start as mjStart,mj_end as mjEnd," +
                        "TRUNCATE(IFNULL((invest_amount/htje),0),2)*100 as investProcess," +
                        "target_state as targetState ,audit_time as auditTime " +
                        "from target_info  " +
                        "where target_state in ('1','2','3') and audit_status='2'");
        Map<String, Object> parameter = new HashMap();
        if (null != targetVo) {
            getTargetParams(targetVo, jpqlBuilder, parameter);
            //状态
            if (StringUtils.isNotBlank(targetVo.getTargetState())) {
                jpqlBuilder.append(" and target_state =:targetState");
                parameter.put("targetState", targetVo.getTargetState());
            }

            //时间区间
            if (null != targetVo.getStartTime()) {
                jpqlBuilder.append(" and DATE_FORMAT(audit_time,'%Y-%m-%d %H:%i:%s') >=:startTime");
                parameter.put("startTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(targetVo.getStartTime()));
            }
            if (null != targetVo.getEndTime()) {
                jpqlBuilder.append("  and DATE_FORMAT(audit_time,'%Y-%m-%d %H:%i:%s') <=:endTime");
                parameter.put("endTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(targetVo.getEndTime()));
            }
        }
        jpqlBuilder.append(" order by audit_time desc");
        Page<Map> targetPage = this.findByPageNativeQuery(page, rows, parameter, jpqlBuilder.toString());
        if(null !=targetPage){
            targetPage.getContent().stream().forEach(map -> {
                String targetState =  map.get("targetState").toString();
                String id = (String) map.get("id");
                //立即投资
                if (StringUtils.isNotBlank(targetState) && targetState.equals(TargetInfo.TARGET_STATE_INVEST)) {
                    Date mjStart = (Date) map.get("mjStart");
                    Date mjEnd = (Date) map.get("mjEnd");
                    if(null != mjStart){
                        if(mjStart.getTime()>System.currentTimeMillis()){
                            map.put("targetState",TargetInfo.TARGET_STATE_OPEN);//即将开放
                        }
                        if(mjEnd.getTime()<System.currentTimeMillis()){
                            map.put("targetState",TargetInfo.TARGET_STATE_BIDDERS);//流标
                        }
                    }
                }
            });
        }
        return targetPage;
    }


    *//**
 * 获取某个标的的投资情况
 *
 * @param page     页码
 * @param rows     行数
 * @param targetId 标的id
 * @return 投资列表
 *//*
    @Override
    public Page findInvestByTargetId(int page, int rows, String targetId) {
        String nativeSql = "SELECT o.target_id,o.buy_amt as buyAmt,o.chanel AS chanel," +
                "o.created_date as createdDate ,u.telephone as telephone" +
                " FROM `order` o, user u WHERE o.user_id = u.id  " +
                "AND o.target_id =:targetId order by o.created_date desc " ;
        Map<String, Object> parameter = new HashMap();
        parameter.put("targetId", targetId);
        Page byPageNativeQuery = this.findByPageNativeQuery(page, rows, parameter, nativeSql);
        return byPageNativeQuery;
    }

    *//**
 * 投资情况中的-某笔投资的总投资人数,总投资金额
 *
 * @param targetId 标的id
 * @return 投资总人数\总金额
 *//*
    @Override
    public String totalInvest(String targetId) {
        Query countQuery = em.createNativeQuery("SELECT COUNT(*) FROM (SELECT DISTINCT user_id " +
                "FROM `order` o,USER u WHERE o.user_id = u.id AND o.target_id =:targetId)t ");
        if (StringUtils.isNotBlank(targetId)) {
            countQuery.setParameter("targetId", targetId);
        }
        StringBuilder jpqlBuilderTotle = new StringBuilder(
                "select SUM(IFNULL(buy_amt,0)) " +
                        "FROM `order` o, user u " +
                        "WHERE o.user_id = u.id  " +
                        "AND o.target_id =:totleId");
        Query totleQuery = em.createNativeQuery(jpqlBuilderTotle.toString());
        if (StringUtils.isNotBlank(targetId)) {
            totleQuery.setParameter("totleId", targetId);
        }
        String castAmount; //投资总金额
        if (null == totleQuery.getSingleResult()) {
            castAmount = "0";
        } else {
            castAmount = totleQuery.getSingleResult().toString();
        }
        long totalCount; //投资总人数
        if (null == countQuery.getSingleResult()) {
            totalCount = 0;
        } else {
            totalCount = Long.parseLong(countQuery.getSingleResult().toString());
        }

        Map<String, Object> totals = new HashMap<String, Object>();
        totals.put("castAmount", castAmount);
        totals.put("totleCount", totalCount);
        return JSON.toJSONString(totals);
    }

    *//**
 * 贷前中理-流标中的项目列表
 *
 * @param page     页码
 * @param rows     行数
 * @param targetVo 筛选条件
 * @return 流标中的项目列表
 *//*
    @Override
    public Page<TargetInfo> findBidderList(int page, int rows, TargetVo targetVo) {
        StringBuilder jpqlBuilder = new StringBuilder(
                " select id,loan_number as loanNumber,telephone,bdrealname,productid,htje," +
                        " invest_amount as investAmount,TRUNCATE(IFNULL((invest_amount/htje),0),2)*100 as investProcess," +
                        " mj_end as mjEnd from target_info WHERE  (now() > mj_end   and target_state =1 ) or  target_state =6");
        Map<String, Object> parameter = new HashMap();
        if (null != targetVo) {
            getTargetParams(targetVo, jpqlBuilder, parameter);
            //募集时间区间
            if (null != targetVo.getStartTime()) {
                jpqlBuilder.append(" and DATE_FORMAT(mj_end,'%Y-%m-%d %H:%i:%s') >=:startTime");
                parameter.put("startTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(targetVo.getStartTime()));
            }
            if (null != targetVo.getEndTime()) {
                jpqlBuilder.append("  and DATE_FORMAT(mj_end,'%Y-%m-%d %H:%i:%s') <=:endTime");
                parameter.put("endTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(targetVo.getEndTime()));
            }
        }
        jpqlBuilder.append(" order by mj_end desc");

        return this.findByPageNativeQuery(page,rows,parameter,jpqlBuilder.toString());
    }

    *//**
 * 更新审核后的标的信息
 *
 * @param targetId    标的id
 * @param auditStatus 审核状态
 * @param suggestion  审核意见
 * @param mjStart     募集开始时间
 * @param rzqx        融资期限
 * @return 审核后的标的信息
 *//*
    @Override
    public TargetInfo updateAuditMsg(String targetId, String auditStatus, String suggestion, String mjStart, String rzqx) {
        TargetInfo targetInfo = targetRepository.findOne(targetId.replaceAll("\"", ""));
        try {
            targetInfo.setMjStart(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(mjStart)); //募集开始时间
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            targetInfo.setAuditTime(dateFormat.parse( dateFormat.format(new Date())));//审核通过时间,发布时间
            targetInfo.setSuggestion(suggestion);//审核意见
            getMjEnd(rzqx, targetInfo); //募集结束时间
            targetInfo.setTargetState(TargetInfo.TARGET_STATE_INVEST);//立即投资
            targetInfo.setAuditStatus(auditStatus); // 审核状态
        } catch (ParseException e) {
            log.info("审核过程中,募集开始时间填写有误");
        }
        return targetInfo;
    }

    *//**
 * 删除风控信息图片
 *
 * @param targetId    标的id
 * @param fileContent 文件保存路径
 *//*
    @Override
    public void removeProPic(String targetId, String fileContent) {
        TargetInfo targetInfo = targetRepository.findById(targetId);
        TargetVo targetVo = JSONObject.toJavaObject(JSON.parseObject(targetInfo.getOtherContent()), TargetVo.class);
        JSONArray proveArray = JSONObject.parseArray(targetVo.getProves());
        //风控信息图片集合
        List<SWLDProvs> provList = JSONArray.parseArray(JSONArray.toJSONString(proveArray), SWLDProvs.class);
        if (null != proveArray) {
            Iterator<SWLDProvs> iterator = provList.iterator();
            while (iterator.hasNext()) {
                SWLDProvs prove = iterator.next();
                //文件路径一致,则删除原有的图片
                if (prove.getFilecontent().equals(fileContent)) {
                    iterator.remove();
                }
            }
        }
        targetVo.setProves(JSON.toJSONString(provList)); //更新风控信息图片
        targetInfo.setOtherContent(JSON.toJSONString(targetVo));//更新标的信息
        targetRepository.save(targetInfo);
    }

    *//**
 * 更新风控信息图片
 *
 * @param oType       文件类型
 * @param fileContent 文件保存路径
 * @param targetId    标的id
 * @return 更新风控信息图片
 *//*
    @Override
    public void updateProPic(String targetId, String fileContent, String oType) {
        TargetInfo targetInfo = targetRepository.findById(targetId);
        TargetVo targetVo = JSONObject.toJavaObject(JSON.parseObject(targetInfo.getOtherContent()), TargetVo.class);
        JSONArray proveArray = JSONObject.parseArray(targetVo.getProves());
        List<SWLDProvs> provList = JSONArray.parseArray(JSONArray.toJSONString(proveArray), SWLDProvs.class);
        SWLDProvs prove = new SWLDProvs();
        prove.setOtype(oType); //更新文件类型
        prove.setFilecontent(fileContent); //更新文件保存路径
        prove.setExtension("");//文件扩展名
        prove.setFileadd("");//文件地址
        prove.setFilename("");//文件名称
        provList.add(prove);//新增风控信息图片
        targetVo.setProves(JSON.toJSONString(provList));//更新风控信息图片
        targetInfo.setOtherContent(JSON.toJSONString(targetVo)); //更新标的信息
        targetRepository.save(targetInfo);

    }

    *//**
 * 更新标的信息
 *
 * @param targetVo 要更新的字段
 *//*
    @Override
    public void updateTargetMsg(TargetVo targetVo) {
        TargetInfo target = targetService.findById(targetVo.getId());
        target.setSortFirst(targetVo.getSortFirst());
        targetService.save(target);
    }

    *//**
 * 查询已满标项目
 * @param page
 * @param rows
 * @param targetVo
 * @return
 *//*
    @Override
    public Page<TargetInfo> findFullScaleList(int page, int rows, TargetVo targetVo) {
        //已满标
        StringBuilder jpqlBuilder = new StringBuilder(
                "select t.id, t.loan_number as loanNumber, t.telephone AS telephone," +
                        " t.bdrealname AS bdrealname,t.productid AS productid," +
                        " t.htje AS htje,t.htqx AS htqx,t.nhsyl AS nhsyl,t.hkfs AS hkfs," +
                        " t.full_date AS fullDate,u.id AS userId" +
                        " from target_info t ,`user` u" +
                        " where t.telephone=u.telephone and t.target_state =:targetState");
        Map<String, Object> parameter = new HashMap();
        parameter.put("targetState",TargetInfo.TARGET_STATE_FULL);
        if (null != targetVo) {
            getTargetParams(targetVo, jpqlBuilder, parameter,"t");
            //融资结束时间-满标时间
            if (null != targetVo.getStartTime()) {
                jpqlBuilder.append(" and DATE_FORMAT(full_date,'%Y-%m-%d %H:%i:%s') >=:rzStartTime");
                parameter.put("rzStartTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(targetVo.getStartTime()));
            }
            if (null != targetVo.getEndTime()) {
                jpqlBuilder.append(" and DATE_FORMAT(full_date,'%Y-%m-%d %H:%i:%s') <=:rzEndTime");
                parameter.put("rzEndTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(targetVo.getEndTime()));
            }
        }
        jpqlBuilder.append(" order by t.created_date desc");
        Page<TargetInfo> targetPage = this.findByPageNativeQuery(page, rows, parameter, jpqlBuilder.toString());
        return targetPage;
    }

    *//**
 * 满标放款
 * @param targetId 标的
 *//*
    @Override
    public void fullScaleLoan(String targetId) throws Exception{
        Map map=new HashMap<>();
        map.put("targetId",targetId);
        //调用Core，手动放款
        String result = HttpClientUtil.httpRequest(CORE_URL, map, HttpMethod.POST);
        JSONObject obj = JSONObject.parseObject(result);

        userService.updateUserType(targetId);

        if(!"SUCCESS".equals(obj.get("state"))){
            //放款失败
            throw new ControllerException("放款失败");
        }
    }


    *//**
 * 获取募集结束日期
 *
 * @param rzqx       融资期限
 * @param targetInfo 标的信息
 *//*
    private void getMjEnd(String rzqx, TargetInfo targetInfo) {
        Calendar mjEnd = Calendar.getInstance();
        mjEnd.setTime(targetInfo.getMjStart());
        mjEnd.add(Calendar.DATE, Integer.parseInt(rzqx));//日期加n天
        targetInfo.setMjEnd(mjEnd.getTime());
    }


    private void getTargetParams(TargetVo targetVo, StringBuilder jpqlBuilder, Map<String, Object> parameter,String str) {
        //借款类型
        if (StringUtils.isNotBlank(targetVo.getProductid())) {
            jpqlBuilder.append(" and "+str+".productid = :productid");
            parameter.put("productid", targetVo.getProductid());
        }
        //用户名
        if (StringUtils.isNotBlank(targetVo.getTelephone())) {
            jpqlBuilder.append(" and "+str+".telephone like:telephone");
            parameter.put("telephone", "%" + targetVo.getTelephone() + "%");
        }
        //真实姓名
        if (StringUtils.isNotBlank(targetVo.getBdrealname())) {
            jpqlBuilder.append(" and "+str+".bdrealname like:bdrealname");
            parameter.put("bdrealname", "%" + targetVo.getBdrealname() + "%");
        }

        //借款编号
        if (StringUtils.isNotBlank(targetVo.getLoanNumber())) {
            jpqlBuilder.append(" and "+str+".loan_number like:loanNumber");
            parameter.put("loanNumber", "%" + targetVo.getLoanNumber() + "%");
        }
    }

    //筛选条件拼接
    private void getTargetParams(TargetVo targetVo, StringBuilder jpqlBuilder, Map<String, Object> parameter) {
        //借款类型
        if (StringUtils.isNotBlank(targetVo.getProductid())) {
            jpqlBuilder.append(" and productid = :productid");
            parameter.put("productid", targetVo.getProductid());
        }
        //用户名
        if (StringUtils.isNotBlank(targetVo.getTelephone())) {
            jpqlBuilder.append(" and telephone like:telephone");
            parameter.put("telephone", "%" + targetVo.getTelephone() + "%");
        }
        //真实姓名
        if (StringUtils.isNotBlank(targetVo.getBdrealname())) {
            jpqlBuilder.append(" and bdrealname like:bdrealname");
            parameter.put("bdrealname", "%" + targetVo.getBdrealname() + "%");
        }

        //借款编号
        if (StringUtils.isNotBlank(targetVo.getLoanNumber())) {
            jpqlBuilder.append(" and loan_number like:loanNumber");
            parameter.put("loanNumber", "%" + targetVo.getLoanNumber() + "%");
        }
    }

}
*/